package ee.smkv.Badminton_score_counter;


import java.util.Stack;

public class Game {

     Stack<State> stateStack = new Stack<State>();

    public Game() {
        stateStack.push( new State(0, 0, true));
    }

    private State getCurrentState(){
        return stateStack.peek();
    }

    public int getMyScore(){
        return getCurrentState().myScore;
    }

    public int getOpponentScore(){
        return getCurrentState().opponentScore;
    }


    public void addPointToOpponent(){
        stateStack.push(getCurrentState().pointToOpponent());
    }

    public void addPointToMe(){
        stateStack.push(getCurrentState().pointToMe());
    }

    public boolean isMyTurn(){
       return getCurrentState().myTurn;
    }

    public boolean isOpponentTurn(){
       return !getCurrentState().myTurn;
    }

    public boolean isGameOver(){
        int min = Math.min(getCurrentState().myScore, getCurrentState().opponentScore);
        int max = Math.max(getCurrentState().myScore , getCurrentState().opponentScore);
        return max >= 21 && ( max - min >= 2 || max == 30);
    }

    public boolean isIWon(){
        return isGameOver() && getCurrentState().myScore > getCurrentState().opponentScore;
    }

    public void undo(){
        if(stateStack.size() > 1){
            stateStack.pop();
        }
    }


    private class State{
        final int myScore;
        final int opponentScore;
        final boolean myTurn;


        private State(int myScore, int opponentScore, boolean myTurn) {
            this.myScore = myScore;
            this.opponentScore = opponentScore;
            this.myTurn = myTurn;
        }

        private State pointToOpponent(){
            return new State(myScore , opponentScore + 1 , false);
        }
        private State pointToMe(){
            return new State(myScore + 1 , opponentScore , true);
        }
    }
}
